package com.cyz.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyz.annotation.AuthCheck;
import com.cyz.common.BaseResponse;
import com.cyz.common.DeleteRequest;
import com.cyz.common.ResultUtils;
import com.cyz.constant.UserConstant;
import com.cyz.exception.ErrorCode;
import com.cyz.exception.ThrowUtils;
import com.cyz.model.dto.user.*;
import com.cyz.model.entity.Picture;
import com.cyz.model.entity.User;
import com.cyz.model.vo.UserLoginVO;
import com.cyz.model.vo.UserVO;
import com.cyz.service.PictureService;
import com.cyz.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private  UserService userService;

    @Resource
    private PictureService pictureService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<Long> register(@RequestBody UserRegisterRequest userRegisterRequest) {
        log.info("用户注册{}", userRegisterRequest);
        // 判断请求参数是否为空
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long result = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public BaseResponse<UserLoginVO> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        log.info("用户登录{}", userLoginRequest);
        // 判断请求参数是否为空
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        UserLoginVO result = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(result);
    }

    /**
     * 获取登录用户信息
     */
    @GetMapping("/get/login")
    public BaseResponse<UserLoginVO> getLoginUser(HttpServletRequest request) {
        log.info("获取登录信息");
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getUserLoginVO(loginUser));
    }

    /**
     * 用户退出登录
     */
    @GetMapping("/logout")
    public BaseResponse<Boolean> logout(HttpServletRequest request) {
        log.info("用户退出登录");
        boolean logoutStatus = userService.userLogout(request);
        return ResultUtils.success(logoutStatus);
    }

    /**
     * 根据id获取用户信息（脱敏）
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        log.info("根据id获取用户信息{}", id);
        // 引用getUserById()方法避免重复代码
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 创建用户（管理员）
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        log.info("管理员创建用户{}", userAddRequest);
        // 校验参数
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(userAddRequest, user);
        // 设置默认密码
        user.setUserPassword(userService.getEncryptPassword("12345678"));
        // 插入数据库
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据id获取用户信息（未脱敏）（管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        log.info("管理员根据id获取用户信息{}", id);
        // 校验参数
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 根据id查询用户
        User user = userService.getById(id);
        // 判断用户是否为空
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 删除用户（管理员）
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        log.info("管理员删除用户{}", deleteRequest);
        // 校验参数
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        boolean result = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(result);
    }

    /**
     * 更新用户（管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        log.info("管理员更新用户{}", userUpdateRequest);

        // 获取用户头像图片对象
        Long userId = userUpdateRequest.getId();
        User beforUpdateUser = userService.getById(userId);
        Picture oldPicture = pictureService.lambdaQuery().eq(Picture::getUrl, beforUpdateUser.getUserAvatar()).one();
        if (oldPicture != null && !Objects.equals(oldPicture.getUrl(), userUpdateRequest.getUserAvatar())){
            //如果头像链接不一样，就删掉老头像，同时删掉数据库中的图片信息
            boolean res = pictureService.deletePictureById(oldPicture.getId(), request);
            ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "删除旧图片失败");
        }
        userService.updateUser(userUpdateRequest);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        log.info("管理员分页获取用户信息列表{}", userQueryRequest);
        // 校验参数
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取分页参数
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        // 将请求参数转换成分页条件
        QueryWrapper<User> userQueryWrapper = userService.getUserQueryWrapper(userQueryRequest);
        // 获取分页
        Page<User> userPage = userService.page( Page.of(current, pageSize), userQueryWrapper);
        // 将数据转换成UserVO类型
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        // 返回
        return ResultUtils.success(userVOPage);
    }

}
